<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #canvas{
      display: block;
      margin: 0 auto;
    }
    form{
      width: 400px;
      text-align: center;
      margin: 10px auto;
    }
  </style>
  <script>
    var ctx;
    var canvasW = 300, canvasH = 227
    var img = new Image()
    img.src = './rhino.jpg'
    var strategies = {
      invertRule: function(data, i){
        data[i] = 255 - data[i]
        data[i + 1] = 255 - data[i + 1]
        data[i + 2] = 255 - data[i + 2]
      },
      grayRule: function(data, i) {
        var avg = (data[i] + data[i+1] + data[i+2]) / 3
        data[i] = avg
        data[i + 1] = avg
        data[i + 2] = avg
      },
      sepiaRule: function(data, i) {
        let red = data[i], green = data[i + 1], blue = data[i + 2];
        data[i] = Math.min(Math.round(0.393 * red + 0.769 * green + 0.189 * blue), 255);
        data[i + 1] = Math.min(Math.round(0.349 * red + 0.686 * green + 0.168 * blue), 255);
        data[i + 2] = Math.min(Math.round(0.272 * red + 0.534 * green + 0.131 * blue), 255);
      }
    }
    // 原始像素
    var original = function() {
      ctx.drawImage(img, 0, 0, canvasW, canvasH)
    }
    
    function pixelRule(rule) {
      ctx.drawImage(img, 0, 0, canvasW, canvasH)
      var imageData = ctx.getImageData(0, 0, canvasW, canvasH)
      var data = imageData.data
      for (var i=0; i<data.length; i+=4) {
        strategies[rule](data, i)
      }
      ctx.putImageData(imageData, 0, 0)
    }
    function draw() {
      ctx = document.getElementById('canvas').getContext('2d')
      ctx.drawImage(img, 0, 0, canvasW, canvasH)
      var inputs = document.getElementsByTagName('input')
      for (const input of inputs) {
        input.addEventListener('change', function(event) {
          switch(event.target.value) {
            case 'grayScale':
              pixelRule('grayRule')
              break
            case 'inverted':
              pixelRule('invertRule')
              break
            case 'sepia':
              pixelRule('sepiaRule')
              break;
            default:
              original()
          }
        })
      }
    }
  </script>
</head>
<body onload="draw()">
  <canvas id="canvas" width="300" height="227"></canvas>
  <form>
    <input type="radio" id="original" name="color" value="original" checked>
    <label for="original">Original</label>
    <input type="radio" id="grayScale" name="color" value="grayScale">
    <label for="grayScale">GrayScale</label>
    <input type="radio" id="inverted" name="color" value="inverted">
    <label for="inverted">Inverted</label>
    <input type="radio" id="sepia" name="color" value="sepia">
    <label for="sepia">Sepia</label>
  </form>
</body>
</html>